<?php
namespace ImiApp\Module\IM\WebSocketController;

use Imi\Server\Server;
use Imi\RequestContext;
use Imi\Aop\Annotation\Inject;
use ImiApp\Module\IM\Enum\MessageType;
use Imi\Controller\WebSocketController;
use ImiApp\Module\IM\Enum\MessageActions;
use Imi\Server\Route\Annotation\WebSocket\WSRoute;
use Imi\Server\Route\Annotation\WebSocket\WSAction;
use Imi\Server\Route\Annotation\WebSocket\WSController;

// use Imi\Server\Route\Annotation\WebSocket\WSConfig;

use Imi\ConnectContext;
use ImiApp\Module\Member\Service\GroupService;
use Imi\Db\Db;
use Imi\Config;
use Yurun\Util\HttpRequest;

/**
 * IM 控制器
 * @WSController(route="/im")
 */
class IMController extends WebSocketController
{
    /**
     * 加入系统房间
     *
     * @WSAction
     * @WSRoute({"action"="im.joinSysRoom"})
     * 
     * @param array $data
     * @return void
     */
    public function joinSysRoom($data)
    {

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        var_dump('ImiApp\Module\IM\WebSocketController\IMController:41',$user);
        


        // var_dump('{"action":"im.joinSysRoom"}');
        if(!isset($data['uid'])){//区域id
            $data['uid'] = 'uid';
        }
        $group = 'im.sysroom.' . $data['uid'];
        $this->server->joinGroup($group, $this->frame->getFd());
        // var_dump($group,RequestContext::getBean('MemberSessionService'));
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');

        // Server::sendToGroup($group, [
        //     'action'    =>  MessageActions::IM_RECEIVE,
        //     'sender'    =>  '系统消息',
        //     'type'      =>  MessageType::SYSTEM,
        //     'content'   =>  $memberSession->getMemberInfo()->username . ' 上线了',
        //     'time'      =>  date('Y-m-d H:i:s'),
        // ]);


        $GroupObj = $this->server->getGroup($group);//获取组对象
        $num = $this->server->getGroup($group)->count();
        var_dump('num',$num);

        $list = $this->server->getGroup($group)->getFds();
        var_dump('list',$list);

        $this->Useronline($user->id);


        // var_dump('groupName',$GroupObj->getFds());
        return [
            'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
            'msg'       =>  'ok',
            'code'     => 1,
        ];
    }




    

    /* 
    * 修改用户在线状态
    */     
    public function Useronline($uid=null,$online = '2')
    {//在线状态:1=离线,2=在线
        var_dump('online:::',$uid,$online);
        if(!$uid){
            $uid = $this->uid;
        }
        $db = Db::query();
        $res = $db->table('fa_user')->where('id','=',$uid)->update(['online_status'=>$online,'logintime'=>time()]);

        // //判断在线时间是否有
        // $res2 = Db::query()->table('fa_online')
        //             ->where('uid','=',$uid)
        //             ->where('on_time','>',1)
        //             // ->where('off_time','=',NULL)
        //             ->order('on_time','desc')
        //             ->select()
        //             ->get();
        // // var_dump('res2',$res2);
        
        // if(!$res2 || !empty($res2['off_time'])){
        //     $insert = Db::query()->table('fa_online')->insert([
        //                                                             'uid'  =>    $uid,
        //                                                             'on_time' => time(),
                                                                    
        //                                                         ]);
        // }


     
        
        
        return $res;
    }

    
    /* 
    * 修改用户离线状态
    */     
    public function offline($uid=null,$online = '1')
    {
        //在线状态:1=离线,2=在线
        if(!$uid){
            $uid = $this->uid;
        }
        return false;
        // $db = Db::query();
        // $res = $db->table('fa_user')->where('id','=',$uid)->update(['online_status'=>$online,'offlinetime'=>time()]);


        // //判断在线时间是否有
        // $res2 = Db::query()->table('fa_online')->where('uid','=',$uid)->where('on_time','>',1)->where('off_time','<',1)->find();
        // if($res2){
        //     $insert = Db::query()->table('fa_online')->update([
        //                                                             's'  =>    time() - $res2['time'],
        //                                                             'off_time' => time(),
                                                                    
        //                                                         ]);
        // }


        // return $res;
    }









    /**
     * 加入群房间
     *
     * @WSAction
     * @WSRoute({"action"="im.joinGroupRoom"})
     * 
     * @param array $data
     * @return void
     */
    public function joinGroupRoom($data)
    {

        
        if(!isset($data['group_id'])){//群id
            return [
                'action'    =>  'joinGroupRoom',//推送群
                'msg'       =>  '需要群id',
                'code'     => -1,
            ];
        }     
        
        $group = 'im.room.group' . $data['group_id'];//群组

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        //判断该用户是否在该群
        // if($user->group_id==4){

            $GroupService =   new GroupService;

            if($GroupService->GroupIsOff($data['group_id'])){
                return [
                    'action'    =>  MessageActions::IM_JOIN_GROUP_ROOM,
                    'msg'       =>  '该群已关闭',
                    'code'     => -1,
                ];
            }

            //不在该群的学生不能加入
            if(!$GroupService->getUid_is_group($user->id,$data['group_id'])){
                return [
                    'action'    =>  MessageActions::IM_JOIN_GROUP_ROOM,
                    'msg'       =>  '不在该群里面',
                    'code'     => -1,
                ];
            }

        // }else{
        //     var_dump('角色组：',$user->group_id);
        // }

        $this->server->joinGroup($group, $this->frame->getFd());

        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'sender'    =>  '群消息',
            'type'      =>  MessageType::TEAM,
            'content'   =>  $user->username . ' 进入群',
            'time'      =>  date('Y-m-d H:i:s'),
        ]);


        $GroupObj = $this->server->getGroup($group);//获取组对象
        $num = $this->server->getGroup($group)->count();
        var_dump('num',$num);

        $list = $this->server->getGroup($group)->getFds();
        var_dump('list',$list);


        // var_dump('groupName',$GroupObj->getFds());
        return [
            'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
            'msg'       =>  'ok',
            'code'     => 1,
        ];
    }


    /**
     * 发送群消息
     *
     * @WSAction
     * @WSRoute({"action"="im.sendGroupMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function sendGroupMsg($data)
    {   
        if(!isset($data['group_id'])){//群id
            return [
                'action'    =>  'sendGroupMsg',//推送群
                'msg'       =>  '需要群id',
                'code'     => -1,
            ];
        }   
        $group = 'im.room.team' . $data['group_id'];//群组

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        //判断该用户是否在该群
        // if($user->group_id==4){
            $GroupService =   new GroupService;

            //不在该群的学生不能加入
            if(!$GroupService->getUid_is_group($user->id,$data['group_id'])){
                return [
                    'action'    =>  MessageActions::IM_JOIN_SYS_ROOM,
                    'msg'       =>  '不在该群里面',
                    'code'     => -1,
                ];
            }

        // }else{
        //     var_dump('sendGroupMsg角色组：',$user->group_id);
        // }

        $this->server->joinGroup($group, $this->frame->getFd());
        

        $ChatGroup = new \ImiApp\Module\Member\Model\ChatGroup;
        $ChatGroup->time = time();

        $ChatGroup->send_uid = $user->id;
        $ChatGroup->time = time();
        $ChatGroup->group_id = $data['group_id'];
        $ChatGroup->content = $data['content'];

        $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
        $ChatGroup->ip = $clientInfo['remote_ip'];        
        $ChatGroup->save();

       


        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'username'    =>  $user->username,
            'send_id'   =>  $user->id,
            'type'      =>  MessageType::TEAM,
            'content'   =>  $data['content'],
            'time'      =>  date('Y-m-d H:i:s'),
        ]);


    }


    





    
    /**
     * 给某个人发送消息
     *
     * @WSAction
     * @WSRoute({"action"="im.sendUserMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function sendUserMsg($data)
    {   
   
        //组，请从这里开始修改 ⌚0325

         /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
         $memberSession = RequestContext::getBean('MemberSessionService');
         $user = $memberSession->getMemberInfo();

        if(isset($data['type'])){
            $type = $data['type'];
        }else{
            $type = 1;
        }

        var_dump('普通消息_____________________');
        var_dump($data);
        var_dump('发送中者ID:',$user->id);

        if($type!=7){
            if($user->id > $data['re_uid']){
                $group = 'im.room.user' . $user->id.'_'.$data['re_uid'];
            }else{
                $group = 'im.room.user' . $data['re_uid'].'_'.$user->id;
            }
            $this->server->joinGroup($group, $this->frame->getFd());
        }



      
        
        var_dump('data',$data,$type);
        if($type==7){

            //消息已读
            $this->msg_status_Read($data['msg_id']);
            var_dump($data);
            return null;
        }elseif($type==1  || $type==11){
             
            

            
 
            // $this->server->joinGroup('im.sysroom.'.$user->id, $this->frame->getFd());

            $db = Db::query();
            $indata['time'] = time();
            $indata['type'] = $type;

            $indata['send_uid'] = $user->id;
            $indata['send_time'] = time();
            $indata['re_uid'] = $data['re_uid'];
            $indata['content'] = $data['content'];
            $indata['image'] = isset($data['image'])?$data['image']:'';
            $indata['group'] = $group;
            $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
            $indata['ip'] = $clientInfo['remote_ip'];
            $res = $db->table('fa_chat')->insert($indata);






        





            Server::sendToGroup($group, [
                'action'    =>  'chat',
                'username'    =>  $user->username,
                'send_uid'   =>  $user->id,
                're_uid'   =>  $data['re_uid'],
                'msg_id'    => $res->getLastInsertId(),
                'type'      =>  $type,
                'content'   =>  $data['content'],
                'image' => isset($data['image'])?$data['image']:'',
                'time'      =>  date('Y-m-d H:i:s'),
            ]);

            //给这个人发送系统消息
            Server::sendToGroup('im.sysroom.'.$data['re_uid'], [
                'action'    =>  'sys',
                'username'    =>  $user->username,
                'send_uid'   =>  $user->id,
                're_uid'   =>  $data['re_uid'],
                'msg_id'    => $res->getLastInsertId(),
                'type'      =>  $type,//类型:1=普通聊天消息,2=心跳,3=订单号,4=系统消息,5=未知,6=未知,7=消息已读,10=语音,11=图片,12=文件
                'content'   =>  $data['content'],
                'time'      =>  date('Y-m-d H:i:s'),
            ]);

            switch ($type) {
                case '1':
                    $title = $data['content'];
                    break;
                case '11':
                    $title = '图片内容';
                    break;
                
                default:
                    $title = '';
                    break;
            }
            $this->update_msg_title($user->id,$data['re_uid'],$title, $res->getLastInsertId());
        }

    }


    /**
     * 消息已读
     *
     * @param int $id
     * @return void
     */
    public function msg_status_Read($id)
    {
        var_dump('在线已阅读ID:'.$id);
        $db = Db::query();
        $res = $db->table('fa_chat')->where('id','=',$id)->update(['msg_status'=>2]);
        //取消定时发送模版
    }

    public function update_msg_title($send_uid,$re_uid,$title,$public_id)
    {
        $url = Config::get('@app.domain').'/api/chat/update_chat_msg';
   

        $requestBody = array(
            'send_uid' => $send_uid,
            're_uid' => $re_uid,
            'title' => $title,
            'public_id' => $public_id
        );
        $http = HttpRequest::newSession();
        $response = $http->post($url, $requestBody);


        // $http = new \Yurun\Util\HttpRequest;
        // $response = $http->get($url)->body();
        // $res_arr = json_decode($response,true);

        // $data['status'] = '7';//'类型:1=动态点赞,2=动态评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息',
        // $data['uid'] = $re_uid;//用户ID
        // $data['user_id'] = $send_uid;//对方ID
        // $db = Db::query();

        
        // $res = $db->table('fa_msg')->where('status','=','7')->where('uid','=',$re_uid)->where('user_id','=',$send_uid)->select()->get();
        // if($res){
        //     $db->table('fa_msg')->where('id','=',$res['id'])->update(['title'=>$title,'public_id'=>$public_id,'time'=>time()]);
        // }else{

        //     $data['time'] = time();
        //     $data['public_id'] = $public_id;
        //     $data['title'] = $title;
        //     $db->table('fa_msg')->insert($data);
        // }

    }

    
    /**
     * 消息已读
     *
     * @param int $id
     * @return void
     */
    public function msg_status_Read2($id)
    {
        var_dump('jigou在线已阅读ID:'.$id);
        $db = Db::query();
        $res = $db->table('fa_chat_jigou')->where('id','=',$id)->update(['msg_status'=>2]);
        //取消定时发送模版

    }    





    // /**
    //  * 给某个人发送消息
    //  *
    //  * @WSAction
    //  * @WSRoute({"action"="im.sendAskUserMsg"})
    //  * 
    //  * @param array $data
    //  * @return void
    //  */
    // public function sendAskUserMsg($data)
    // {   
   
       

    //     /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
    //     $memberSession = RequestContext::getBean('MemberSessionService');
    //     $user = $memberSession->getMemberInfo();

    //     var_dump('382Ask_____________________');
    //     var_dump($data);


    //     if(isset($data['type'])){
    //         $type = $data['type'];
    //     }else{
    //         $type = 1;
    //     }
        

    //     if($type!=7){
    //         if($user->id > $data['re_uid']){
    //             $group = 'im.room.user.sys' . $user->id.'_'.$data['re_uid'];
    //         }else{
    //             $group = 'im.room.user.sys' . $data['re_uid'].'_'.$user->id;
    //         }
    //         var_dump('group_sendAskUserMsg',$group);
    //         $this->server->joinGroup($group, $this->frame->getFd());
    //     }





    //     // var_dump('data',$data,$type);
    //     if($type==7){
    //         //消息已读
    //         $this->msg_status_Read2($data['msg_id']);
    //         return null;
    //     }elseif($type==1 || $type==11){
             


    //         // $this->server->joinGroup('im.sysroom.'.$user->id, $this->frame->getFd());

    //         $db = Db::query();
    //         $indata['time'] = time();


    //         $indata['send_uid'] = $user->id;
    //         $indata['send_time'] = time();
    //         $indata['re_uid'] = $data['re_uid'];
    //         $indata['content'] = $data['content'];
    //         $indata['admin_id'] = $data['admin_id'];
    //         $indata['group'] = $group;
    //         $clientInfo = $this->server->getSwooleServer()->getClientInfo($this->frame->getFd());
    //         $indata['ip'] = $clientInfo['remote_ip'];
    //         $res  = $db->table('fa_chat_jigou')->insert($indata);





    //         Server::sendToGroup($group, [
    //             'action'    =>  'chat',
    //             'username'    =>  $user->username,
    //             'send_uid'   =>  $user->id,
    //             'type'      =>  $type,
    //             'msg_id'    => $res->getLastInsertId(),
    //             'admin_id' => $data['admin_id'],
    //             'content'   =>  $data['content'],
    //             'time'      =>  date('Y-m-d H:i:s'),
    //         ]);


            
    //         //给这个人发送系统消息
    //         Server::sendToGroup('im.sysroom.'.$data['re_uid'], [
    //             'action'    =>  'sys',
    //             'username'    =>  $user->username,
    //             'send_uid'   =>  $user->id,
    //             'msg_id'    => $res->getLastInsertId(),
    //             'type'      =>  '4',//类型:1=普通聊天消息,2=心跳,3=订单号,4=系统消息,5=未知,6=未知,7=消息已读,10=语音,11=图片,12=文件
    //             'content'   =>  $data['content'],
    //             'time'      =>  date('Y-m-d H:i:s'),
    //         ]);

    //     }


    // }


    
    /**
     * 加入某个人的消息
     *
     * @WSAction
     * @WSRoute({"action"="im.joinUserMsg"})
     * 
     * @param array $data
     * @return void
     */
    public function joinUserMsg($data)
    {   
   
         /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
         $memberSession = RequestContext::getBean('MemberSessionService');
         $user = $memberSession->getMemberInfo();
       
        if($user->id > $data['re_uid']){
            $group = 'im.room.user' . $user->id.'_'.$data['re_uid'];
        }else{
            $group = 'im.room.user' . $data['re_uid'].'_'.$user->id;
        }
        
        $this->server->joinGroup($group, $this->frame->getFd());
        
        return [
                'action'    =>  'joinUserMsg',
                'msg'       =>  '用户聊天',
                'code'     => 1,
        ];


    }



     /**
     * 推送内容
     *
     * @WSAction
     * @WSRoute({"action"="im.push"})
     * 
     * @param array $data
     * @return void
     */
    public function push($data)
    {
        var_dump('im.push',$data);
        $content = $data['content'] ?? '';
        if('' === $content)
        {
            return;
        }
        
        if(mb_strlen($content) > 999)
        {
            $content = mb_substr($content, 0, 999);
        }


        if(!isset($data['roomId'])){//区域id
            $data['roomId'] = 'com';
        }
        $group = 'im.room.' . $data['roomId'];

        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $user = $memberSession->getMemberInfo();
        

        $GroupObj = $this->server->getGroup($group);//获取组对象
        var_dump($group.'人数:',$GroupObj->count());


        
        

        
        // var_dump('组列表',$this->server->getGroups());
        // var_dump('getGroup',$GroupObj);
        

        if($memberSession->getMemberInfo()->group_id==3){//1老板 2机构 3老师 4学生

            
            $time = date('Y-m-d H:i:s');
            defer(function() use($user, $content, $time, $group){
                Server::sendToGroup( $group, [
                    'action'    =>  MessageActions::IM_RECEIVE,
                    'type'      =>  MessageType::SYSTEM,
                    'sender'    =>  $user->username,
                    'user_id'   =>  $user->id,
                    'content'   =>  $content,
                    'time'      =>  $time,
                ]);
            });
            return [
                'action'    =>  MessageActions::IM_SEND,
            ];



        }else{
            return [
                'action'    =>  MessageActions::IM_SEND,
                'msg'       =>  '非机构！',
                'code'     => -1,
            ];
        }
        


      
    }






    // /**
    //  * 推送群内容
    //  *
    //  * @WSAction
    //  * @WSRoute({"action"="im.pushteam"})
    //  * 
    //  * @param array $data
    //  * @return void
    //  */
    // public function pushteam($data)
    // {
        
    //     $content = $data['content'] ?? '';
    //     if('' === $content)
    //     {
    //         return;
    //     }
        


    //     if(!isset($data['group_id'])){//区域id
    //         return [
    //             'action'    =>  'pushteam',//推送群
    //             'msg'       =>  '需要群id',
    //             'code'     => -1,
    //         ];
    //     }

    //     $group = 'im.room.team' . $data['group_id'];//群组

    //     /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
    //     $memberSession = RequestContext::getBean('MemberSessionService');
    //     $user = $memberSession->getMemberInfo();
        

    //     $GroupObj = $this->server->getGroup($group);//获取组对象
    //     var_dump($group.'人数:',$GroupObj->count());
        
    //     $Fds = $GroupObj->getFds();
    //     foreach($Fds as $fd){
    //         $memberId = ConnectContext::get('memberId', null, $fd);//注释
    //         var_dump('fd'.$fd,'ID:'.$memberId);
    //     }
    //     // var_dump('组列表',$this->server->getGroups());
    //     // var_dump('getGroup',$GroupObj);
        

    //     if($memberSession->getMemberInfo()->group_id==3){//1老板 2机构 3老师 4学生

            
    //         $time = date('Y-m-d H:i:s');
    //         defer(function() use($user, $content, $time, $group){
    //             Server::sendToGroup( $group, [
    //                 'action'    =>  MessageActions::IM_RECEIVE,
    //                 'type'      =>  MessageType::TEAM,
    //                 'sender'    =>  $user->username,
    //                 'user_id'   =>  $user->id,
    //                 'content'   =>  $content,
    //                 'time'      =>  $time,
    //             ]);
    //         });
    //         return [
    //             'action'    =>  MessageActions::IM_SEND,
    //         ];



    //     }else{
    //         return [
    //             'action'    =>  MessageActions::IM_SEND,
    //             'msg'       =>  '非机构！',
    //             'code'     => -1,
    //         ];
    //     }
        


      
    // }







    /**
     * 加入房间
     *
     * @WSAction
     * @WSRoute({"action"="im.joinRoom2"})
     * 
     * @param array $data
     * @return void
     */
    public function joinRoom($data)
    {
        $group = 'im.room.' . $data['roomId'];
        $this->server->joinGroup($group, $this->frame->getFd());
        var_dump($group,RequestContext::getBean('MemberSessionService'));
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        var_dump($memberSession);
        Server::sendToGroup($group, [
            'action'    =>  MessageActions::IM_RECEIVE,
            'sender'    =>  '系统消息',
            'type'      =>  MessageType::SYSTEM,
            'content'   =>  $memberSession->getMemberInfo()->username . ' 进来了',
            'time'      =>  date('Y-m-d H:i:s'),
        ]);
        return [
            'action'    =>  MessageActions::IM_JOIN_ROOM,
        ];
    }

    /**
     * 发送内容
     *
     * @WSAction
     * @WSRoute({"action"="im.send"})
     * 
     * @param array $data
     * @return void
     */
    public function send($data)
    {
        $content = $data['content'] ?? '';
        if('' === $content)
        {
            return;
        }
        if(mb_strlen($content) > 999)
        {
            $content = mb_substr($content, 0, 999);
        }
        /** @var \ImiApp\Module\Member\Service\MemberSessionService $memberSession */
        $memberSession = RequestContext::getBean('MemberSessionService');
        $sender = $memberSession->getMemberInfo()->username;
        $roomId = $data['roomId'];
        $time = date('Y-m-d H:i:s');
        defer(function() use($sender, $content, $time, $roomId){
            Server::sendToGroup('im.room.' . $roomId, [
                'action'    =>  MessageActions::IM_RECEIVE,
                'type'      =>  MessageType::CHAT,
                'username'    =>  $sender,
                'send_uid'    =>  $memberSession->getMemberInfo()->id,
                'content'   =>  $content,
                'time'      =>  $time,
            ]);
        });
        return [
            'action'    =>  MessageActions::IM_SEND,
        ];
    }


    // public function get_msg_type($group_id){
    //     switch ($group_id) {
    //         case '1':
    //             return MessageType::BOSS;
    //             break;
    //         case '2':
    //             return MessageType::JIGOU;
    //             break;
    //         case '3':
    //             return MessageType::TEACHER;
    //             break;
    //         case '4':
    //             return MessageType::STUDENT;
    //             break;

    //         case '5':
    //             return MessageType::AREA;
    //             break;
    //         case '6':
    //             return MessageType::SYSTEM;
    //             break;
    //         case '7':
    //             return MessageType::TEAM;
    //             break;
    //         case '8':
    //             return MessageType::UNREAD;
    //             break;

    //         default:
    //             # code...
    //             break;
    //     }
        
    // }
    
}
